<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, User-Agent');

error_reporting(0);
function m_exit($code,$title,$text,$data=[]){
    $back['code'] = $code;
    $back['title'] = $title;
    $back['text'] = $text;
   $back['data'] = $data;
    echo json_encode($back,JSON_UNESCAPED_UNICODE);
    exit();
}

$ver = 1;
$db = '\think\facade\Db';
$exp = '../maolin/';
$super = $_GET['super'];
require_once __DIR__ . '/superkey.php';
$getkey = $_GET['getkey'].'';
$type = $_GET['type'];
$key = $_GET['key'];   
$phost = '0.0.0.0:8082';
$host = 'http://'.$phost;
$site =  $host.'/go-cqhttp/api/'.$load['bot'].'/';


function cqapi($type,$data,$ctq,$ffff = 'no',$url = false) {
    global $site,$load;

    if($url == false){
        $url = $site.'api?name='.$type;
    }
    $json_data = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $ctq);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json_data)
    ));
    $result = curl_exec($ch);
    curl_close($ch);
    $json = json_decode($result,JSON_UNESCAPED_UNICODE);
    if($ffff == 'no') {
        if ($json['detail'] != null) {
            header("Status: 400");
            m_exit(400, '操作失败', $json['detail']);
        }
    }
    if($json['retcode'] == 404){
        header("Status: 400");
        m_exit(400,'操作失败','错误的API名称');
    }
    return [$result,$json];
}

//如果是key模式
if($key != null) {
    //读取KEY信息和BOT信息
    $load = $db::name('vue_key')
        ->where('key', $key)
        ->find();
    //验证KEY是否超时
    if (time() >= $load['time']) {
        header("Status: 400");
        m_exit(400, 'key过期', 'key过期');
    }

    //设置初始url
    $site =  $host.'/go-cqhttp/api/'.$load['bot'].'/';


    //检测KEY
    if($type == 'delkeyout'){
        $data = [
            'code' => 200,
            'bot' => $load['bot'],
            'time' => $load['time'],
        ];
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        $db::name('vue_key')->where('key',$key)->delete();
        exit();
    }
    //检测KEY
    if($type == 'getkeyout'){
        $data = [
            'code' => 200,
            'bot' => $load['bot'],
            'time' => $load['time'],
        ];
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit();
    }

    //开启BOT
    if($type == 'start_bot'){
        $site =  $host.'/go-cqhttp/api/'.$load['bot'].'/process';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $site);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($status_code == 204) {
            m_exit(200,'暂停成功','暂停成功');
        } else {
            m_exit(200,'暂停失败','暂停失败');
        }
    }

    //暂停BOT
    if($type == 'stop_bot'){
        $site =  $host.'/go-cqhttp/api/'.$load['bot'].'/process';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $site);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($status_code == 204) {
            m_exit(200,'暂停成功','暂停成功');
        } else {
            m_exit(200,'暂停失败','暂停失败');
        }
    }
    //删除BOT
    if($type == 'del_bot'){
        $site =  $host.'/go-cqhttp/api/'.$load['bot'].'?with_file=true';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $site);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($status_code == 204) {
            m_exit(200,'删除成功','删除成功');
        } else {
            m_exit(200,'删除失败','此账号已经删除');
        }
    }
    //查看配置文件
    if($type == 'get_cfg'){
        $datafile = __DIR__.'/';
        $sm = scandir($datafile);
    }
    //发送消息到控制台
    if($type == 'send_svmsg'){
        $msg = $_GET['msg'];
        if($msg == null){
            $msg = '';
        }
        $data = array('input' => $msg);
        $url = $site.'process/logs';
        $datax = cqapi('process/logs',$data,'POST','yes',$url);
        echo $datax[0];
    }

    //读取登录账号
    if($type == 'get_login_info'){
        $data = array('no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //读取客户端
    if($type == 'get_online_clients'){
        $data = array('no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //读取好友列表
    if($type == 'get_friend_list'){
        $data = array('no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //读取单向好友列表
    if($type == 'get_unidirectional_friend_list'){
        $data = array('no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //读取群列表
    if($type == 'get_group_list'){
        $data = array('no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //读取群信息
    if($type == 'get_group_info'){

        $gqq = intval($_GET['gqq']);
        if($gqq <= 10000){
            header("Status: 400");
            m_exit(400,'读取失败','请输入目标qq群号');
        }
        $data = array('group_id'=>$gqq,'no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //读取群历史记录
    if($type == 'get_group_msg_history'){

        $gqq = intval($_GET['gqq']);
        if($gqq <= 10000){
            header("Status: 400");
            m_exit(400,'读取失败','请输入目标qq群号');
        }
        $data = array('group_id'=>$gqq,'no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //读取群成员列表
    if($type == 'get_group_member_list'){

        $gqq = intval($_GET['gqq']);
        if($gqq <= 10000){
            header("Status: 400");
            m_exit(400,'读取失败','请输入目标qq群号');
        }

        $data = array('group_id'=>$gqq,'no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //读取精华列表
    if($type == 'get_essence_msg_list'){

        $gqq = intval($_GET['gqq']);
        if($gqq <= 10000){
            header("Status: 400");
            m_exit(400,'读取失败','请输入目标qq群号');
        }

        $data = array('group_id'=>$gqq,'no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //撤回消息
    if($type == 'delete_msg'){

        $gmsg = intval($_GET['gmsg']);
        if($gmsg <= 0){
            header("Status: 400");
            m_exit(400,'读取失败','请输入正确的消息ID');
        }

        $data = array('message_id'=>$gmsg);
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //根据消息ID获取消息
    if($type == 'get_msg'){

        $gmsg = intval($_GET['gmsg']);
        if($gmsg <= 0){
            header("Status: 400");
            m_exit(400,'读取失败','请输入正确的消息ID');
        }

        $data = array('message_id'=>$gmsg);
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }

    //发送消息
    if($type == 'send_msg'){
        $gtype = $_GET['gtype'];  //群=group 好友=private
        $guserid = intval($_GET['guserid']); //QQ号
        $ggid = intval($_GET['ggid']);  //群号
        $gmsg = $_GET['message'];  //消息
        if($gtype == null){
            header("Status: 400");
            m_exit(400,'读取失败','未设置类型');
        }
        if($gtype == 'group'){
            if($ggid <= 10000){
                header("Status: 400");
                m_exit(400,'读取失败','请输入正确的QQ群');
            }
            $data = array('message_type'=>'group','group_id' => $ggid,'message'=>$gmsg);
            $datax = cqapi($type,$data,'POST');
            echo $datax[0];
        }else{
            if($gtype == 'private'){
                if($guserid <= 10000){
                    header("Status: 400");
                    m_exit(400,'读取失败','请输入正确的QQ号');
                }
                $data = array('message_type'=>'private','user_id' => $guserid,'message'=>$gmsg);
                $datax = cqapi($type,$data,'POST');
                echo $datax[0];
            }else{
                header("Status: 400");
                m_exit(400,'读取失败','错误类型');
            }
        }
    }

    //删除好友
    if($type == 'delete_friend'){
        $gqq = intval($_GET['gqq']);
        if($gqq <= 10000){
            header("Status: 400");
            m_exit(400,'读取失败','请输入目标QQ号');
        }
        $data = array('user_id'=>$gqq,'no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //删除单向好友
    if($type == 'delete_unidirectional_friend'){
        $gqq = intval($_GET['gqq']);
        if($gqq <= 10000){
            header("Status: 400");
            m_exit(400,'读取失败','请输入目标QQ号');
        }
        $data = array('user_id'=>$gqq,'no_cache' => 'true');
        $datax = cqapi($type,$data,'POST');
        echo $datax[0];
    }
    //读取陌生人消息
    if($type == 'get_stranger_info'){
        $gqq = intval($_GET['gqq']);
        if($gqq <= 10000){
            header("Status: 400");
            m_exit(400,'读取失败','请输入目标QQ号');
        }
        $data = array('user_id'=>$gqq,'no_cache' => 'true');
        $datax = cqapi('get_group_list',$data,'POST');
        echo $datax[0];
    }
    //读取控制台日志
    if ($type == 'getlog') {
            $url = $host.'/go-cqhttp/api/' . $load['bot'] . '/process/logs';
            $data = array();
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            curl_close($ch);

            $datax['info'] = json_decode($result, true);

            $url = $host.'/go-cqhttp/api/' . $load['bot'] . '/process/status';
            $data = array();
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            curl_close($ch);

        $url = $host.'/go-cqhttp/api/status';
        $data = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result2 = curl_exec($ch);
        curl_close($ch);

            $datax['bot'] = $load;
            $datax['sv'] = json_decode($result2, true);
            $datax['status'] = json_decode($result, true);
        echo json_encode($datax, JSON_UNESCAPED_UNICODE);
    }

    exit();
}

if($getkey == $superkey){
    if($type == 'addbot') {
        $user = intval($_GET['username']);
        $password = $_GET['password'];
        if($user <= 10000){
            header("Status: 400");
            m_exit(400,'注册失败','你没有输入正确的QQ号');
        }
        if($password == null){
            header("Status: 400");
            m_exit(400,'注册失败','你没有输入密码');
        }

        $url = $host.'/go-cqhttp/api/'.$user;
        $data = array('password' => $password);
        $json_data = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($json_data)
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($result,true);
        if($data['uin']  >= 1){
            m_exit(200,'注册成功','你可以返回进行操作BOT。');
        }else{
            header("Status: 400");
            m_exit(400,'注册失败1','该账号已经被绑定。');
        }
    }
    if($type == 'getkey') {
        $bot = intval($_GET['bot']);
        $uid = intval($_GET['uid']);
        if($bot == null){
            header("Status: 400");
            m_exit(400,'账号错误','本服务器不存在此BOT或未填写账号');
        }
        if($uid <= 0){
            header("Status: 400");
            m_exit(400,'账号错误','未登录V6账号');
        }
        $key = md5(time() . $getkey . $superkey);
        $newdata = [
            'bot' => $bot,
            'uid' => $uid,
            'time' => time() + 1800,
            'key' => $key,
        ];
        $db::name('vue_key')->insert($newdata);
        $data = [
            'code' => 200,
            'key' => $key,
            'text' => '有效期到：' . date('H:i:s', (time() + 1800)),
        ];
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit();
    }
    exit(json_encode(['code'=>200,'msg'=>'密钥正确'], JSON_UNESCAPED_UNICODE));
}else{
    if($getkey != null) {
        header("Status: 400");
        exit(json_encode(['code'=>400,'msg'=>'密钥错误'], JSON_UNESCAPED_UNICODE));
    }
}






//echo $superkey;

    echo '<a href="?super=1">点击这里生成超级密钥</a>';
    if($super == 1){
        $fileName = __DIR__."/maolin.lock";
        if (!file_exists($fileName)) {
            $rand = md5(time());
            file_put_contents(__DIR__ . '/superkey.php', "<?php \n".'$superkey = "'.$rand.'";');
            fopen($fileName, 'w');
            echo '生成成功：你的密钥是[ '.$rand.' ] 如果忘记了密码可以查看目录 phpserver/maolin/superkey.php';
        }else{
            echo '你已经生成过超级密钥了  如果忘记了密码可以查看目录 phpserver/maolin/superkey.php';
        }
    }

